<?php

/**
 * PartialStoreOrder
 * 
 * 
 * 
 * @package    ProdAssistant
 * @subpackage model
 * @author     Paweł Świtalla
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class PartialStoreOrder
{
  public function save($storeOrderItems, $parameters, $user)
  {
    $deliverers = array();
    $orders = new Doctrine_Collection('StoreOrder');
    foreach($storeOrderItems as $itemId => $deliverer)
    {
      if(isset($deliverers[$deliverer]))
      {
        $deliverers[$deliverer][] = $itemId;
      }
      else
      {
        $deliverers[$deliverer] = array($itemId);
      }
    }
    
    foreach($deliverers as $deliverer => $items)
    {
      $order = new StoreOrder();
      $originalDemand = Doctrine_Core::getTable('ProductionDemand')->find($parameters['demand_id']);
      
      $demandItems = new Doctrine_Collection('DemandItems');
      $query = Doctrine_Query::create();
      foreach($items as $item)
      {
        $record = new DemandItems();
        $query
            ->select('d.*')
            ->from('DemandItems d')
            ->where('d.demand_id = ?', $originalDemand->getId())
            ->andWhere('d.item_id = ?', $item);
        $value = $query->fetchOne();
        $record
            ->setItemId($item)
            ->setDemandId($originalDemand->getId())
            ->setValue($value->getValue());
        $demandItems->add($record);
      }
      
      $order->setDemand($originalDemand);
      $order->setUser($user);
      $order->setDelivererId($deliverer);
      $order->setStatus(0);
      $order->setAddressId($parameters['address_id']);
      $order->save();
      
      foreach($demandItems as $item)
      {
        $orderItems = new OrderItems();
        $orderItems->setOrderId($order->getId());
        $orderItems->setItemId($item->getItemId());
        $orderItems->setOrderedValue($item->getValue());
        $orderItems->save();
      }
      $order->setNumber("ZM-".$order->getDemand()->getProject()->getShortcut()."-".date("Y-m-d", strtotime($order->getCreatedAt()))."-".$order->getId());
      $order->save();
      $orders->add($order);
    }
    return $orders;
  }
}
